package cn.com.w.jdk8.demo.controller;


import cn.com.w.jdk8.demo.util.ThreadPoolUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/lock")
public class LockController {

    /**
     * 锁对象
     */
    public Lock lock = new ReentrantLock();

    @GetMapping("/")
    public String lock(){
        boolean b = lock.tryLock();
        if (b) {
                try {
                    long start = System.currentTimeMillis();
                    System.out.println(Thread.currentThread().getName() +"获取到锁，开始执行");
                    ThreadPoolUtil.execute(() -> {
                        Thread.currentThread().setName("deal-data-");
                        dealData();
                    });

                    TimeUnit.SECONDS.sleep(6);
                    long end = System.currentTimeMillis();
                    System.out.println("共执行="+ (end - start) + "毫秒");
                } catch (InterruptedException e) {
                    System.out.println("local report thread is interrupted");
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
        } else {
            System.out.println(Thread.currentThread().getName() +"未获取到锁");
        }
        return "";
    }


    private void dealData() {
        try {
            System.out.println(Thread.currentThread().getName() +"处理数据");
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
